﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CITWebsite.Models;
using CITWebsite.Captcha;

using DTO.Models;

namespace CITWebsite.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        private const string TempDataKey = "CaptchaData";
        private const string SessionKey = "CaptchaSolution";

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************
        public ActionResult Login()
        {
            var captchaData = TempData[TempDataKey] as CaptchaData;

            if (captchaData == null)
            {
                captchaData = new CaptchaData();
            }
            else
            {
                ModelState.AddModelError("Attempt", "Không đúng mã");
            }

            return View(captchaData);
        }

        // **************************************
        // URL: /Account/Login
        // **************************************
        [HttpPost]
        public ActionResult Login(CaptchaData captchaData)
        {
            //FormsService.SignOut();
            Session.Timeout = 30000;
            var solution = Session[SessionKey];
            //always remove after reading
            Session.Remove(SessionKey);

            ActionResult result;

            if (Request.Form["submit"] == null)//just refresh the page but preserve the form data
            {
                result = View(captchaData);
            }
            else if (solution != null && string.Compare(solution.ToString(), captchaData.Attempt, true) == 0)//success
            {
                
                string username = Request["username"];
                string password = Request["password"];
                string passwordencrypt = MD5.Encrypt(password, username + "key", true);
                
                DataRepository dr = new DataRepository();
                if (dr.UserProvider.checklogin(username, passwordencrypt))
                {
                    bool remember = Request["remember"] == null ? false : true;
                    FormsService.SignIn(username, remember);

                    string userType = dr.UserProvider.GetUserByUsername(username).Type;
                    Session[Common.SessionCookiesUserType] = userType;
                    if (remember)
                    {
                        Response.Cookies[Common.SessionCookiesUserType].Value = userType;
                        Response.Cookies[Common.SessionCookiesUserType].Expires = DateTime.Now.AddDays(30);
                    }

                    result = RedirectToAction("Index", "Home");
                }
                else
                {
                    result = RedirectToAction("Login");
                }
            }
            else//failed
            {
                captchaData.Attempt = string.Empty;
                TempData.Add(TempDataKey, captchaData);

                result = RedirectToAction("Login");
            }

            return result;
        }

        public ActionResult getImageCaptcha()
        {

            var builder = new XCaptcha.ImageBuilder(4, new CustomCanvas(), new CustomTextStyle(), new CustomDistort(), new CustomNoise());
            //Uncomment for default version
            //var builder = new XCaptcha.ImageBuilder();

            var result = builder.Create();

            Session.Add(SessionKey, result.Solution);

            return new FileContentResult(result.Image, result.ContentType);

        }


        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();
            return RedirectToAction("Login", "Account");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


    }
}
